//
//  LoginOrRegisterController.swift
//  登录/注册界面
//
//  Created by smile on 2019/6/6.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//导入RxSwift
import RxSwift

class LoginOrRegisterController: BaseTitleController {
    
    
    /// 登陆按钮
    @IBOutlet weak var btLogin: UIButton!
    
    
    /// 注册按钮
    @IBOutlet weak var btRegister: UIButton!
    
    override func initViews() {
        super.initViews()
        
        //圆角
        ViewUtil.showLargeRadius(view: btLogin)
        ViewUtil.showLargeRadius(view: btRegister)
        
        //边框
        btLogin.showColorPrimaryBorder()
        btRegister.showColorPrimaryBorder()
    }
    
    /// 按下
    /// 改变按钮的背景颜色
    ///
    /// - Parameter sender: 那个按钮
    @IBAction func touchDown(_ sender: UIButton) {
        //更改按钮的背景颜色
        sender.backgroundColor=UIColor(hex: COLOR_PRIMARY)
    }
    
    
    /// 抬起
    /// 还原按钮的背景颜色
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func touchUp(_ sender: UIButton) {
        touchUpOutside(sender)
        
        //因为两个按钮都关联到同一个方法了
        if btLogin == sender {
            //登录按钮
            toLogin()
        } else {
            //注册按钮
            toRegister()
        }
    }
    
    /// 跳转到登录页面
    func toLogin() {
        print("LoginOrRegisterController toLogin")
        
        //实例化控制器
        let controller=storyboard!.instantiateViewController(withIdentifier: "Login")
        
        //将控制器压入导航控制器
        navigationController!.pushViewController(controller, animated: true)
        
        //ToastUtil.short("这是提示框！")
        
//        ToastUtil.showLoading()
//
//        DispatchQueue.main.asyncAfter(deadline: .now()+3.0) {
//            ToastUtil.hideLoading()
//        }
    }
    
    /// 跳转到注册界面
    func toRegister(type:SSDKPlatformType?=nil, avatar:String?=nil,nickname:String?=nil,openId:String?=nil) {
        print("LoginOrRegisterController toRegister")
        
        //获取到Storyboard
        
        //实例化控制器
        let controller=storyboard!.instantiateViewController(withIdentifier: "Register") as! RegisterController
        
        //传递参数
        controller.type = type
        controller.avatar=avatar
        controller.nickname=nickname
        controller.openId=openId
//        controller.openId="12kjsogfdgfj"
        
        //将控制器压入导航控制器
        navigationController!.pushViewController(controller, animated: true)
    }
    
    /// 抬起（按钮外面）
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func touchUpOutside(_ sender: UIButton) {
        sender.backgroundColor=UIColor.white
    }
    
    // MARK: - 第三方登录
    
    /// 微信登录按钮点击
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onWechatLoginClick(_ sender: Any) {
        print("LoginOrRegisterController onWechatLoginClick")
        
        otherLogin(.typeWechat)
    }
    
    
    /// QQ登录按钮点击
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onQQLoginClick(_ sender: Any) {
        print("LoginOrRegisterController onQQLoginClick")
        
//        //获取用户信息
//        ShareSDK.getUserInfo(.typeQQ) { (state:SSDKResponseState, user, error) in
//            if state == .success {
//                //QQ登录成功了
//
//                //就可以获取到昵称，头像，OpenId
//                let nickname=user?.nickname
//                let avatar=user?.icon
//                let openId=user?.credential.token
//
////                let openId:String?="dkgkjdflglsijdfdsf"
//
//                print("LoginOrRegisterController onQQLoginClick success:\(nickname),\(avatar),\(openId)")
//
//                //跳转到注册界面
////                self.toRegister(avatar: avatar, nickname: nickname, openId: openId)
//                self.continueLogin(type: .typeQQ,avatar: avatar!, nickname: nickname!, openId: openId!)
//            } else {
//                //登录失败
//
//                print("LoginOrRegisterControler onQQLoginClick failed:\(error)")
//
//                ToastUtil.short("登录失败，请稍后再试！")
//            }
//        }
        
        //使用重构后的方法
        otherLogin(.typeQQ)
        
        
    }
    
    /// 通用第三方登录
    ///
    /// - Parameter type: type description
    func otherLogin(_ type:SSDKPlatformType)  {
            //获取用户信息
            ShareSDK.getUserInfo(type) { (state:SSDKResponseState, user, error) in
                if state == .success {
                    //QQ登录成功了
    
                    //就可以获取到昵称，头像，OpenId
                    let nickname=user?.nickname
                    let avatar=user?.icon
//                    let openId=user?.credential.token
    
                    let openId:String?="skklsgdfgfgl"
    
                    print("LoginOrRegisterController otherLogin success:\(nickname),\(avatar),\(openId)")
    
                    //跳转到注册界面
    //                self.toRegister(avatar: avatar, nickname: nickname, openId: openId)
                    self.continueLogin(type: type,avatar: avatar!, nickname: nickname!, openId: openId!)
                } else {
                    //登录失败
    
                    print("LoginOrRegisterControler otherLogin failed:\(error)")
    
                    ToastUtil.short("登录失败，请稍后再试！")
                }
            }

    }
    
    /// 继续登录
    ///
    /// - Parameters:
    ///   - avatar: 昵称
    ///   - nickname: 头像
    ///   - openId: 第三方登录后用户Id
    func continueLogin(type:SSDKPlatformType,avatar:String,nickname:String,openId:String) {
        print("LoginOrRegisterController continueLogin:\(avatar),\(nickname),\(openId)")
        
        var api:Observable<DetailResponse<Session>?>!
        
        var qqId:String?
        var weiboId:String?
        var wechatId:String?
        
        if type == .typeQQ {
            //把openId传递到qq_id参数上面
            api = Api.shared.login(qq_id:openId)
            qqId=openId
        }else if type == .typeWechat{
            //把openId传递到wechat_id参数上面
            api = Api.shared.login(wechat_id:openId)
            wechatId=openId
        } else {
            //把openId传递到weibo_id参数上面
            api = Api.shared.login(weibo_id:openId)
            weiboId=openId
        }
        
        //先调用登录接口
        //如果接口返回用户不存在（根据code判断）
        //就跳转到补充用户资料页面
        //如果存在其实就完成了登录
        //后面的逻辑和正常登录一样
        api.subscribe({ data in
            //登录成功
            
            //表示用户已经注册了（补充资料了）
            
            //把登录完成的事件回调到AppDelegate
            AppDelegate.shared.onLogin(data!.data!)
            
            //统计第三方登录成功事件
            AnalysisUtil.onLogin(success: true, qqId: qqId, weiboId: weiboId)
        }) { (baseResponse, error) -> Bool in
            //登录失败
            
            //统计第三方登录失败事件
            AnalysisUtil.onLogin(success: false, qqId: qqId, weiboId: weiboId)
            
            //判断具体的错误类型
            if let baseResponse = baseResponse {
                //请求成功了
                //并且服务端返回了错误信息
                
                //判断错误码
                if 1010 == baseResponse.status {
                    //用户未注册
                    
                    //跳转到补充用户资料页面
                    self.toRegister(type:type,avatar: avatar, nickname: nickname, openId: openId)
                    
                    //返回true就表示我们处理了错误
                    return true
                }
                
                
            }
            
            
            //这里我们就不管是什么错误类型了
            //直接让框架处理
            return false
            
        }.disposed(by: disposeBag)
        
    }
    
    
    /// 微博登录按钮点击
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onWeiboLoginClick(_ sender: Any) {
        print("LoginOrRegisterController onWeiboLoginClick")
        
//        //获取用户信息
//        ShareSDK.getUserInfo(.typeSinaWeibo) { (state, user, error) in
//            if state == .success {
//                //登录成功
//
//                //这里可以获取到昵称，头像，OpenId等信息
//                let nickname=user?.nickname
//                let avatar=user?.icon
//                let openId=user?.credential.token
//
//                print("LoginOrRegisterController onWeiboLoginClick login success:\(nickname),\(avatar),\(openId)")
//
//                self.continueLogin(type: .typeSinaWeibo, avatar: avatar!, nickname: nickname!, openId: openId!)
//            }else {
//                //登录失败
//                print("LoginOrRegisterController onWeiboLoginClick login failed:\(error)")
//            }
//        }
        
        //使用重构后的方法
        otherLogin(.typeSinaWeibo)
    }
    
    
    /// 网易邮箱登录按钮点击
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onNeteaseLoginClick(_ sender: Any) {
        print("LoginOrRegisterController onNeteaseLoginClick")
    }
    
//    /// 视图即将可见
//    ///
//    /// - Parameter animated: <#animated description#>
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//
//        print("LoginOrRegisterController viewWillAppear")
//
//        //隐藏导航栏
//        navigationController!.setNavigationBarHidden(true, animated: true)
//    }
//
//    /// 视图即将消息
//    /// will:即将
//    /// did:已经
//    /// 其他方法也是遵循这个命名规范的
//    ///
//    /// - Parameter animated: <#animated description#>
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//
//        print("LoginOrRegisterController viewWillDisappear")
//
//        //显示导航栏
//        //因为其他界面可能不需要隐藏
//        navigationController!.setNavigationBarHidden(false, animated: true)
//    }
    
    
    /// 是否隐藏导航栏
    ///
    /// - Returns: <#return value description#>
    override func hideNavigationBar() -> Bool {
        return true
    }
    
    
//    /// 登录类型
//    ///
//    /// - QQ: QQ登录
//    /// - WEIBO: 微博登录
//    enum LoginType {
//        case QQ
//        case WEIBO
//    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
